package com.dankegongyu.lib.common.util;

import android.app.Application;
import android.content.Intent;
import android.net.Uri;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;

import androidx.fragment.app.Fragment;

/**
 * @author wupuquan
 * @version 1.0
 * @since 2019-08-19 20:53
 */
public class DKRouter {

    private DKRouter() {
        throw new AssertionError();
    }

    public static void setDebugMode(boolean isDebug) {
        if (isDebug) {
            // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog(); // 打印日志
            ARouter.openDebug(); // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
            ARouter.printStackTrace(); // 打印日志的时候打印线程堆栈
        }
    }

    /**
     * 加上同步锁
     */
    public static synchronized void init(Application application) {
        ARouter.init(application);
    }

    /**
     * Router初始化是否完成
     */
    public static boolean hasRouterInited() {
        try {
            ARouter.getInstance();
            // 如果ARouter初始化没有完成，getInstance()会抛异常
            return true;
        } catch (Throwable e) {
//            e.printStackTrace();
        }
        return false;
    }

    private static void ensureRouterInit() {
        if (!hasRouterInited()) {
            init(GlobalContext.getApplication());
        }
    }

    public static void inject(Object obj) {
        // 1.ARouter.getInstance()可能抛异常
        // 2.https://github.com/alibaba/ARouter/issues/115
        ensureRouterInit();
        ARouter.getInstance().inject(obj);
    }

    public static Postcard build(String path) {
        ensureRouterInit();
        return ARouter.getInstance().build(path);
    }

    public static Postcard build(String path, String group) {
        ensureRouterInit();
        return ARouter.getInstance().build(path, group);
    }

    public static Postcard build(Uri url) {
        ensureRouterInit();
        return ARouter.getInstance().build(url);
    }

    public static void startActivityForResult(Fragment fragment, Postcard postcard, int requestCode) {
        if (fragment == null || fragment.getActivity() == null || postcard == null) {
            return;
        }
        try {
            LogisticsCenter.completion(postcard);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(fragment.getActivity(), postcard.getDestination());
        intent.putExtras(postcard.getExtras());
        fragment.startActivityForResult(intent, requestCode);
        if (postcard.getEnterAnim() != 0 && postcard.getExitAnim() != 0) {
            fragment.getActivity().overridePendingTransition(postcard.getEnterAnim(), postcard.getExitAnim());
        }
    }

}
